package com.xuebang.admin.util;

import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Component;

import net.sf.uadetector.OperatingSystem;
import net.sf.uadetector.UserAgentStringParser;
import net.sf.uadetector.service.UADetectorServiceFactory;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

@Component
public class UserAgentParser {

	private final UserAgentStringParser parser = UADetectorServiceFactory
			.getResourceModuleParser();
	private final Cache<String, net.sf.uadetector.UserAgent> cache = CacheBuilder
			.newBuilder().maximumSize(100).expireAfterWrite(2, TimeUnit.HOURS)
			.build();

	public UserAgent parse(final String userAgentString) {
		net.sf.uadetector.UserAgent result = cache
				.getIfPresent(userAgentString);
		if (result == null) {
			result = parser.parse(userAgentString);
			cache.put(userAgentString, result);
		}

		UserAgent userAgent = new UserAgent();

		userAgent.setType(result.getType().name());
		userAgent.setFamily(result.getFamily().name());
		userAgent.setName(result.getName());
		userAgent.setVersion(result.getVersionNumber().toVersionString());

		OperatingSystem os = result.getOperatingSystem();
		userAgent.setOsFamily(os.getFamily().name());
		userAgent.setOsName(os.getName());
		userAgent.setOsVersion(os.getVersionNumber().toVersionString());

		return userAgent;
	}

	public static void main(String[] args) {
		UserAgentParser parser = new UserAgentParser();
		String ss[] = {
				"Mozilla/4.0",
				"Mozilla/4.0 (Windows; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)",
				"Mozilla/4.0 (Mozilla/4.0; MSIE 7.0; Windows NT 5.1; FDM; SV1; .NET CLR 3.0.04506.30)",
				"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; GTB5; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506; InfoPath.2; OfficeLiveConnector.1.3; OfficeLivePatch.0.0)",
				"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; Media Center PC 6.0; InfoPath.3; MS-RTC LM 8; Zune 4.7)",
				"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)",
				"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.43 Safari/537.31",
				"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; 360SE)",
				"Mozilla/5.0 (Linux; U; Android 1.5; de-de; HTC Magic Build/CRB17) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1" };
		for (String s : ss) {
			UserAgent ua = parser.parse(s);
			System.out.println(ua);
		}
	}
}
